<template>
  <div class="m-4 mr-0 mt-0 overflow-hidden bg-white">
    <BasicTree
      search
      defaultExpandAll
      placeholder="请输入部门名称"
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      :clickRowToExpand="false"
      :treeData="treeData"
      :fieldNames="{ key: 'id', title: 'name' }"
      @select="handleSelect"
      ref="asyncExpandTreeRef"
    />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, unref, nextTick } from 'vue';

  import { BasicTree, TreeActionType, TreeItem } from '/@/components/Tree';
  import { getDeptTreeByPage } from '/@/api/admin/dept';

  export default defineComponent({
    name: 'DeptTree',
    components: { BasicTree },

    emits: ['select'],
    setup(_, { emit }) {
      const treeData = ref<TreeItem[]>([]);
      const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);

      async function fetch() {
        const children = (await getDeptTreeByPage()) as unknown as TreeItem[];
        treeData.value = [
          {
            id: '',
            key: '-1',
            name: '所有部门',
            children,
          },
        ];
        nextTick(() => {
          unref(asyncExpandTreeRef)?.expandAll(true);
        });
      }

      function handleSelect(keys) {
        emit('select', keys[0]);
      }

      onMounted(() => {
        fetch();
      });
      return { treeData, handleSelect, asyncExpandTreeRef };
    },
  });
</script>
